// hyb_yl/mysubpages/pages/shopinfo/index.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    checked: false,
    items: [{
      name: '退货无忧￥0.40 可享一次免费上门取件',
      checked: false,
      value: '退货无忧￥0.40 可享一次免费上门取件'
    }],
    addrkey: true,
    price: '',
    addresslist: [],
    repicelist: [],
    addbox: true,
    medicbox: true,
    parway: ["货到付款", "在线预付"],
    payindex: 1,
    maskbox: true, //配送方式
    delivery: ["药房配送", "京东物流"],
    deliveryIndex: 0,
    num: 1,
    price: '', //单价
    sum: '', //总价
    frieght: 6, // 运费
    sales: 0.40, //退货
    invoice: true, //发票
    electron: ["电子发票"],
    invoiceTitle: ["个人", "单位"], //发票抬头
    unitName: '', //单位名称
    ratepayer: '', //纳税号
    invoiceIndex: 0,
    invoiceCont: ["明细", "不开发票"], //发票内容
    partIndex: 1, //选择发票内容下标
    coupon: true, //优惠券初始值
    couponTitle: [{
        usable: 0,
        title: "可用优惠券"
      },
      {
        usable: 1,
        title: "不可用优惠券"
      }
    ], //选择可用优惠和不可用优惠
    couponIndex: 0,
    instru: true,
    already: [],
    arr: [],
    favorable: '', //优惠价格
    commodity: [],
    druglist: true,
    countmoney: 0,
    summoney: 0,
    // 总重
    feight: 0,
    statu:1
  },
  touchmove:function(){},
  chooseradio: function() {
    this.setData({
      checked: !this.data.checked
    })
    this.getsum()
  },
  num: function(e) {
    console.log(e)
    var commodity = this.data.commodity
    var index = e.target.dataset.index
    commodity[index].num = e.detail.value
    var num = this.data.num
    this.setData({
      commodity: commodity
    })
  },
  getnum: function(e) {
    console.log(e)
    var index = e.currentTarget.dataset.index
    var commodity = this.data.commodity
    console.log(commodity)
    var mostgt = parseInt(this.data.mostgt)
    console.log(mostgt)
    if (commodity[index].num < 1) {
      wx.showToast({
        title: '至少输入一个商品',
        icon: 'none'
      })
      commodity[index].num=1
      this.setData({
        commodity: commodity,
      })
      this.getsum()
    } else {
      this.getsum()
    }
    if (commodity[index].mostgt == 0) {
      if(commodity[index].num >parseInt(commodity[index].snum)){
        wx.showToast({
          title: '最多不超过'+commodity[index].snum+'件',
          icon:'none'
        })
        commodity[index].num =commodity[index].snum
        this.setData({
          commodity: commodity,
        })
        this.getsum()
      }
    }else{
      if(commodity[index].num >parseInt(commodity[index].mostgt)){
        wx.showToast({
          title: '最多不超过'+commodity[index].mostgt+'件',
          icon: 'none'
        })
        commodity[index].num =commodity[index].mostgt
        this.setData({
          commodity: commodity,
        })
        this.getsum()
      }
    } 
  },
  add: function(e) {
    console.log(e)
    var index = e.currentTarget.dataset.index
    var commodity = this.data.commodity
    commodity[index].num++;
    if (commodity[index].mostgt == 0) {
      if(commodity[index].num >parseInt(commodity[index].snum)){
        wx.showToast({
          title: '最多不超过'+commodity[index].snum+'件',
          icon:'none'
        })
        commodity[index].num =commodity[index].snum
        this.setData({
          commodity: commodity,
        })
        this.getsum()
      }
    }else{
      if(commodity[index].num >parseInt(commodity[index].mostgt)){
        wx.showToast({
          title: '最多不超过'+commodity[index].mostgt+'件',
          icon: 'none'
        })
        commodity[index].num =commodity[index].mostgt
        this.setData({
          commodity: commodity,
        })
        this.getsum()
      }
    } 
    this.setData({
      commodity:commodity
    })
   
    this.getsum()
  },
  suv: function(e) {
    console.log(e)
    var index = e.currentTarget.dataset.index
    var commodity = this.data.commodity
    if (commodity[index].num<= 1) {
      wx.showToast({
        title: '至少1件',
        icon: 'none'
      })
      commodity[index].num = 1
      this.setData({
        commodity:commodity
      })
    } else {
      
      commodity[index].num--;
      this.setData({
        commodity:commodity
      })
      // commodity[index].num=1
      // this.setData({
      //   commodity: commodity
      // })
    }
    this.getsum()
  },
  //计算总价的封装方法
  getsum() {
    var commodity = this.data.commodity;
    console.log(commodity)
    var countmoney = 0
    console.log(countmoney)
    var feight = 0
    var g_kuaidi =0
    var summoney = this.data.summoney
    var a=0
    for(var i=0;i<commodity.length;i++){
      feight += parseFloat((commodity[i].num * commodity[i].gg_ke).toFixed(3))
      countmoney += parseFloat((commodity[i].num * commodity[i].smoney).toFixed(2))
      g_kuaidi = commodity[i].g_kuaidi
    }
    feight =parseFloat(feight).toFixed(3)
    countmoney = parseFloat(countmoney).toFixed(2)
    summoney = (parseFloat(countmoney) + parseFloat(g_kuaidi)).toFixed(2)
    console.log(feight)
    console.log(countmoney)
    console.log(summoney)
    this.setData({
      feight:feight,
      countmoney:countmoney,
      g_kuaidi:g_kuaidi,
      summoney:summoney
    })
  },
 
  // changeradio:function(){
  //   var items = this.data.items;
  //   items[0].checked = !(items[0].checked);
  //   this.setData({
  //     items: items
  //   });
  // },
  onPageScroll: function(e) {
    if (e.scrollTop > 150) {
      this.setData({
        addrkey: false
      })
    } else {
      this.setData({
        addrkey: true
      })
    }
  },
  address: function() {
    wx.navigateTo({
      url: '/hyb_yl/onesubpages/pages/shipping/shipping',
    })
  },
  tian: function() {
    // wx.navigateTo({
    //   url: '/hyb_yl/onesubpages/pages/address/address',
    // })
    var that = this
    wx.chooseAddress({
      success: function(res) {
        console.log(JSON.stringify(res))
        var userAddress = res.provinceName + res.cityName + res.countyName + res.detailInfo
        console.log(userAddress)
        var addresslist = {
          userAddress: userAddress,
          userName: res.userName,
          userPhone: res.telNumber
        }
        console.log(addresslist)
        that.setData({
          addresslist: addresslist
        })
        wx.setStorageSync("Address", addresslist)
      },
      fail: function(err) {
        console.log(JSON.stringify(err))
        console.info("收货地址授权失败");
        wx.showToast({
          title: '授权失败，您将无法进行下单支付;重新授权请删除小程序后再次进入',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  pattern: function() {
    this.setData({
      maskbox: !this.data.maskbox

    })
  },
  close: function() {
    this.setData({
      maskbox: !this.data.maskbox,
      payindex: 1,
      deliveryIndex: 0
    })
  },
  // 选择支付方式
  choosepay: function(e) {
    this.setData({
      payindex: e.currentTarget.dataset.index
    })
  },
  choosedelivery: function(e) {
    this.setData({
      deliveryIndex: e.currentTarget.dataset.index
    })
  },
  question: function() {
    this.setData({
      maskbox: !this.data.maskbox
    })
  },
  //打开发票弹出框
  bill: function() {
    this.setData({
      invoice: !this.data.invoice
    })
  },
  //关闭发票弹出框
  closeInvoice: function() {
    this.setData({
      invoice: !this.data.invoice,
      invoiceIndex: 0,
      parway: 0,
    })
  },
  // 选择发票抬头
  chooseInvoice: function(e) {
    this.setData({
      invoiceIndex: e.currentTarget.dataset.index
    })
  },
  // 选择发票内容
  selectCont: function(e) {
    this.setData({
      partIndex: e.currentTarget.dataset.index
    })

  },
  //单位名称获取
  unitName: function(e) {
    this.setData({
      unitName: e.detail.value
    })
  },
  //纳税号获取
  ratepayer: function(e) {
    this.setData({
      ratepayer: e.detail.value
    })
  },
  // 确认发票
  questionBill: function() {
    if (this.data.invoiceIndex == 1) {
      var unitName = this.data.unitName;
      var ratepayer = this.data.ratepayer;
      if (unitName == "") {
        wx.showToast({
          title: '请填写单位名称',
          icon: 'none'
        })
      } else if (ratepayer == "") {
        wx.showToast({
          title: '请填写购买方纳税号',
          icon: 'none'
        })
      } else {
        this.setData({
          invoice: !this.data.invoice
        })
      }
    } else if (this.data.invoiceIndex == 0) {
      this.setData({
        invoice: !this.data.invoice
      })
    }
  },
  //点击优惠券弹出框
  discounts: function() {
    this.setData({
      coupon: !this.data.coupon
    })
  },
  //关闭优惠券弹出框
  closecou: function() {
    this.setData({
      coupon: !this.data.coupon
    })
  },
  //可用优惠劵按钮选择
  selectCoupon: function(e) {
    this.setData({
      couponIndex: e.currentTarget.dataset.index
    })
  },
  // 优惠券中的点击确认
  questionCoupon: function() {
    this.setData({
      coupon: !this.data.coupon
    })
  },
  //使用说明弹出框
  instructions: function() {
    this.setData({
      instru: !this.data.instru
    })
  },
  know: function() {
    this.setData({
      instru: !this.data.instru
    })
  },
  druglist: function() {
    this.setData({
      druglist: !this.data.druglist
    })
  },
  closedrug: function() {
    this.setData({
      druglist: !this.data.druglist
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    console.log(JSON.parse(options.arr))
    // var commodity = JSON.parse(options.newarr)
    var commodity = JSON.parse(options.arr)
    console.log(commodity)
    var addressid = commodity.addressid
    var g_kuaidi = commodity.g_kuaidi
    var ifcfy = options.ifcfy
    console.log(ifcfy)
    var mostgt = commodity[0].mostgt
    var gg_id = commodity.gg_id
    this.setData({
      commodity: commodity,
      price: commodity.price,
      num: commodity.num,
      // countmoney: commodity.countmoney,
      g_kuaidi: g_kuaidi,
      mostgt: mostgt,
      ifcfy: ifcfy,
      gg_id: gg_id,
      addressid: addressid
    })
    this.getsum()
    var already = wx.getStorageSync("coupon")
    var address = wx.getStorageSync("Address")
    this.setData({
      addresslist: address,
      already: already
    })
    if (this.data.addresslist == "") {
      this.setData({
        addbox: true
      })
    } else {
      this.setData({
        addbox: false
      })
    }
    var medicemess = wx.getStorageSync("medicemess")

    var repicelist = medicemess.slice(0, 1)
    this.setData({
      repicelist: repicelist
    })
    if (repicelist == "") {
      this.setData({
        medicbox: true
      })
    } else {
      this.setData({
        medicbox: false
      })
    }
    var bgc = wx.getStorageSync('color')
    wx.setNavigationBarColor({
      frontColor: "#ffffff",
      backgroundColor: bgc,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    console.log('222')
    // console.log(options.price)
    var already = wx.getStorageSync("coupon")
    var address = wx.getStorageSync("Address")
    this.setData({
      already: already,
      addressid: address.addressId,
    })
    var medicemess = wx.getStorageSync("medicemess")
    var repicelist = medicemess.slice(0, 1)
    this.setData({
      repicelist: repicelist
    })
    if (repicelist == "") {
      this.setData({
        medicbox: true
      })
    } else {
      this.setData({
        medicbox: false
      })
    }
    let pages = getCurrentPages();
    let currPage = pages[pages.length - 1];
    if (currPage.data.j_id) {
      var that = this
      var j_id = currPage.data.j_id
      app.util.request({
        'url': 'entry/wxapp/User.detailmyjd',
        data: {
          j_id: j_id
        },
        success: function(res) {
          console.log(res)
          that.setData({
            age: res.data.age,
            sex: res.data.sex,
            phone: res.data.tel,
            username: res.data.names,
            medicbox: false,
            cf_id: currPage.data.cf_id
          })
        }
      })

    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    // var address = wx.getStorageSync("Address")
    // this.setData({
    //   addresslist: address
    // })
    // if (this.data.addresslist == "") {

    // } else {
    //   this.setData({
    //     addbox: false
    //   })
    // }
    var medicemess = wx.getStorageSync("medicemess")
    var repicelist = medicemess.slice(0, 1)
    this.setData({
      repicelist: repicelist
    })
    if (repicelist == "") {

    } else {
      this.setData({
        medicbox: false
      })
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },
  submit: function(e) {
    console.log(e)
    var that = this
    var that = this
    if (that.data.addresslist == "") {
      wx.showToast({
        title: '请先填写收货地址',
        icon: 'none'
      })
    } else if (that.data.medicbox && that.data.ifcfy == 1) {
      wx.showToast({
        title: '请先填写处方信息',
        icon: 'none'
      })
    } else {
      var commodity = that.data.commodity
      var g_kuaidi = commodity.g_kuaidi //运费
      var gg_id = commodity.gg_id //规格id
      var sid = commodity.sid //商品id
      var countmoney = e.currentTarget.dataset.ycountmoney //商品金额
      var feight = e.currentTarget.dataset.feight
      var num = e.currentTarget.dataset.num
      var summoney = e.currentTarget.dataset.summoney //进行各种折扣之后的金额
      var u_id = e.currentTarget.dataset.u_id
      var totalMoney = that.data.totalMoney //实际金额
      var deliverMoney = that.data.deliverMoney //运费
      var addressid = that.data.addressid
      console.log(addressid)
      //支付
      
      app.util.request({
        'url': 'entry/wxapp/Goods.creatorder',
        data: {
          g_kuaidi: g_kuaidi,
          gg_id: gg_id,
          sid: sid,
          countmoney: countmoney,
          feight: feight,
          num: num,
          realTotalMoney: summoney,
          totalMoney: totalMoney,
          deliverMoney: deliverMoney,
          u_id: u_id,
          addressid: addressid,
          openid: wx.getStorageSync('openid')
        },
        success: function(res) {
          console.log(res)
          var orderNo = res.data
          app.util.request({
            'url': 'entry/wxapp/Goods.pay',
            header: {
              "Content-Type": "application/xml"
            },
            method: "GET",
            data: {
              openid: wx.getStorageSync('openid'),
              z_tw_money: summoney,
              orderNo: orderNo
            },
            success: function(res) {
              console.log(res);
              wx.requestPayment({
                'timeStamp': res.data.timeStamp,
                'nonceStr': res.data.nonceStr, //字符串随机数
                'package': res.data.package,
                'signType': res.data.signType,
                'paySign': res.data.paySign,
                success: function(res) {
                  console.log(res)
                  wx.reLaunch({
                    url: '/hyb_yl/userCommunicate/pages/order/order',
                  })
                }
              })
            }
          })
        }
      })
    }

  },
  // 选择微信收货地址
  address: function() {
    console.log(1)
    var region = [];
    var arr1 = [];
    var that = this
    wx.chooseAddress({
      success: function(res) {
        console.log("res")
        console.log(res)
        console.log(JSON.stringify(res))
        var name = res.userName
        var phone = res.telNumber
        region.push(res.provinceName, res.cityName, res.countyName)
        var address = res.detailInfo
        var addlist = {
          name: res.userName,
          phone: res.telNumber,
          address: res.detailInfo,
          region: region,
          label: -1,
          addlabel: ""
        }
        console.log(addlist)
        //添加收货人信息
        var userName = addlist.name
        var userPhone = addlist.phone
        var userAddress = addlist.region[0] + '-' + addlist.region[1] + '-' + addlist.region[2] + '-' + addlist.address
        app.util.request({
          'url': 'entry/wxapp/Goods.creatuseraddress',
          data: {
            openid: wx.getStorageSync('openid'),
            userName: userName,
            userPhone: userPhone,
            userAddress: userAddress
          },
          success: function(res) {
            console.log(res)
            var addressid = res.data.addressId
            wx.setStorageSync("Address", res.data)
            that.setData({
              addressid: addressid,
              addresslist: res.data
            })
            if (res.data == "") {
              that.setData({
                addbox: true
              })
            } else {
              that.setData({
                addbox: false
              })
            }
          }
        })
        arr1 = wx.getStorageSync("Address") || [];
        that.setData({
          addresslist: arr1
        })
      },
      fail: function (err) {
        that.openConfirm()
        
        
      }
    })
  },
  openConfirm: function () {
    wx.showModal({
      content: '检测到您没打开地址权限，是否去设置打开？',
      confirmText: "确认",
      cancelText: "取消",
      success: function (res) {
        if (res.confirm) {
          wx.openSetting({
            success: (res) => {
              console.log(res)
            } //打开设置面板
          })
        } else {
          console.log('用户点击取消')
        }
      }
    });
  },

})